package com.ai.module.chat.config;

import com.ai.module.chat.config.interceptor.GptMybatisHandler;
import com.ai.module.chat.config.interceptor.MangeUserInterceptor;
import com.ai.module.websocket.handler.PortalHandshakeInterceptor;
import com.ai.module.chat.util.MrHeOpenAiService;
import io.github.asleepyfish.config.ChatGPTProperties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.net.UnknownHostException;
import java.time.Duration;
import java.util.List;

/**
 * @author: MrHe
 * @create: 2023-09-02 10:42
 * @description:
 **/
@Configuration
@CrossOrigin("*")
public class GptWebMvcConfiguration implements WebMvcConfigurer {

    @Autowired
    private GptMybatisHandler gptMybatisHandler;
    @Resource
    private ChatGPTProperties properties;

    @Autowired
    MangeUserInterceptor mangeUserChatInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                //是否发送Cookie
                .allowCredentials(true)
//                .allowedOrigins("*")
                //放行哪些原始域
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .exposedHeaders("*")
                .allowedOriginPatterns("*")
               //  .allowedOrigins("http://127.0.0.1:5500")
               //  .allowedOrigins("http://8.216.66.88:9999")

        ;

    }

    @Autowired
    private PortalHandshakeInterceptor handshakeInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(mangeUserChatInterceptor)
                .addPathPatterns("/member/**")
                .excludePathPatterns("/**/login","*index.html","/","","/**/register")
        ;


    }


    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider ) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                mappings.removeIf(mapping -> mapping.getPatternParser() != null);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }



    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        // 创建模板
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 设置序列化工具
        GenericJackson2JsonRedisSerializer jsonRedisSerializer =
                new GenericJackson2JsonRedisSerializer();
        // key和 hashKey采用 string序列化
        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        // value和 hashValue采用 JSON序列化
        redisTemplate.setValueSerializer(jsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);
        return redisTemplate;
    }

//    @Bean webSocket
//    public ServerEndpointExporter serverEndpointExporter() {
//        return new ServerEndpointExporter();
//    }


    @Bean
    public MrHeOpenAiService mrHeOpenAiUtil(){
        return new MrHeOpenAiService(properties,Duration.ZERO);
    }

    @Bean("restTemplate")
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }


}
